import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MenuItem } from '@/api/menu'
import { getLoginInfoAPI, getUserTreeListAPI, SysUser } from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  //登录后的token
  const token = ref(localStorage.getItem('token') || '')

  // 用户信息
  const userInfo = ref<SysUser>()

  // 用户权限列表
  const permissions = ref<string[]>([])

  // 用户菜单列表
  const userMenusRef = ref<MenuItem[]>()

  // 设置用户权限
  const setPermissions = (newPermissions: string[]) => {
    permissions.value = newPermissions
  }

  // 获取用户菜单
  const userMenus = computed(() => {
    if (userMenusRef.value && userMenusRef.value.length > 0) return userMenusRef.value
    const menus = localStorage.getItem('menus')
    return JSON.parse(menus as string)
  })

  // 设置用户菜单
  const setUserMenus = (menus: MenuItem[]) => {
    userMenusRef.value = menus
    localStorage.setItem('menus', JSON.stringify(menus))
  }

  // 检查是否有权限
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission)
  }

  // 清空用户信息
  const clearUserInfo = () => {
    permissions.value = []
    userMenusRef.value = []
  }

  const login = (_token: string, _userInfo: SysUser) => {
    token.value = _token
    userInfo.value = _userInfo
    localStorage.setItem('token', _token) // 保存 token 到 localStorage
    loadUserMenus();
  }

  // 加载用户菜单权限
  const loadUserMenus = async () => {
    try {
      const response = await getLoginInfoAPI()
      if (response.code === 200) {
        setPermissions(response.result.permissions.map(e => e.value))
      } else {
        ElMessage.error('加载菜单权限失败')
      }
      const response2 = await getUserTreeListAPI(userInfo.value?.id as string)
      if (response2.code === 200) {
        setUserMenus(response2.result)
      } else {
        ElMessage.error('加载菜单权限失败')
      }
    } catch (error) {
      console.error('加载用户菜单失败:', error)
      ElMessage.error('加载菜单失败')
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = Object.assign({})
    localStorage.removeItem('token') // 清除 token
  }

  return {
    token,
    permissions,
    userMenus,
    login,
    logout,
    setPermissions,
    setUserMenus,
    hasPermission,
    clearUserInfo
  }
})
